<template>
  <page-header-wrapper :title="false">
    <a-card title="已开发票列表">
      <a-tabs v-model="tab" type="card">
        <a-tab-pane key="1" tab="已审核未开票"></a-tab-pane>
        <a-tab-pane key="2" tab="已审核已开票"></a-tab-pane>
      </a-tabs>
      <div class="table-page-search-wrapper">
        <a-form-model :model="queryParam" layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="合同编号">
                <a-input type="text" v-model="queryParam['filter[contract_no]']" placeholder="请输入合同编号" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="提交顾问">
                <a-select
                  show-search
                  v-model="queryParam['filter[adviser_uid]']"
                  placeholder="选择顾问姓名"
                  :filter-option="filterOption"
                >
                  <a-select-option v-for="(item,index) in adviserOpts" :key="index" :value="index">{{item}}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="申请时间">
                <a-range-picker @change="onCreateAt" />
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="开票时间">
                  <a-range-picker @change="onCheckAt" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="是否完善">
                  <a-select
                    v-model="queryParam['filter[is_perfect]']"
                    placeholder="发票信息是否已完善"
                  >
                    <a-select-option :value="1">是</a-select-option>
                    <a-select-option :value="2">否</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="发票抬头">
                  <a-input type="text" v-model="queryParam['filter[header]']" placeholder="输入开票抬头" />
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="!advanced && 8 || 24" :sm="24">
                <span class='table-page-search-submitButtons' :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                  <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                  <a-button style="margin-left: 8px" @click="resetSearch">重置</a-button>
                  <a @click="toggleAdvanced" style="margin-left: 8px">
                    {{ advanced ? '收起' : '展开' }}
                    <a-icon :type="advanced ? 'up' : 'down'" />
                  </a>
                </span>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <s-table
        bordered
        ref="table"
        :row-key="(record) => record.id"
        :columns="invoiceColumns"
        :data="invoiceData"
      >
        <div slot="title">
          <a-button size="small" icon="export" type="primary" @click="exportInvoice">导出发票</a-button>
        </div>
        <template slot="contract_no" slot-scope="text,record">
          <a-button v-if="text == '合并合同'" type="link" @click="toDetail(record.id)">{{text}}</a-button>
          <a-button v-else type="link" @click="$router.push({ name: 'ContractDetail', params: { id: record.contract_id } })">{{text}}</a-button>
        </template>
        <template slot="company_name" slot-scope="text,record">
          {{text}}({{record.tax_point}}%)
        </template>
        <template slot="tm_name" slot-scope="text,record">
          {{text}}{{record.pt_name}}
        </template>
        <template slot="username" slot-scope="text, record">
          <a-tag>{{text}}</a-tag><br>
          <a-tag>{{record.group_type}}组</a-tag><br>
          <a-tag>{{record.leader_name}}</a-tag>
        </template>
        <template slot="action" slot-scope="text,record">
          <a-button v-if="record.info == 0 && tab == 2" size="small" type="danger" @click="uploadModal(record.id)" style="margin-right:5px">上传信息</a-button>
          <a-button v-else-if="record.info == 1 && tab == 2" size="small" disabled style="margin-right:5px">信息已完善</a-button>
          <a-button v-if="tab != 2" size="small" type="danger" style="margin-right:5px" @click="getInvoice(record.id)">信息</a-button>
          <a-button size="small" type="primary" @click="toDetail(record.id)">详情</a-button>
        </template>
      </s-table>
    </a-card>
    <a-modal
      title="补充发票信息"
      v-model="visible"
      @ok="submitUpload"
    >
      <a-form-model
        ref="invoiceForm"
        :model="invoiceForm"
        :rules="invoiceRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="发票编号" prop="invoice_num">
          <a-input type="text" v-model="invoiceForm.invoice_num" />
        </a-form-model-item>
        <a-form-model-item label="物流公司" prop="express_name">
          <a-input type="text" v-model="invoiceForm.express_name" />
        </a-form-model-item>
        <a-form-model-item label="物流单号" prop="express_num">
          <a-input type="text" v-model="invoiceForm.express_num" />
        </a-form-model-item>
        <a-form-model-item label="电子档发票">
          <a-upload
            name="file"
            :multiple="true"
            :action="uploadUrl"
            :headers="header"
            @change="handleChange"
          >
            <a-button> <a-icon type="upload" /> 上传电子档发票 </a-button>
          </a-upload>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal
      destroy-on-close
      title="开票信息确认"
      v-model="visible2"
      :width="700"
      :footer="null"
    >
      <a-form-model
        ref="ruleForm"
        :model="invoiceForm"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="选择开票公司">
          <a-input readOnly v-model="invoiceForm.company_name" />
        </a-form-model-item>
        <a-divider orientation="left">填写纳税人信息</a-divider>
        <a-form-model-item label="发票模版">
          <a-button type="link" icon="download">水动力发射基地离开房间</a-button>
        </a-form-model-item>
        <!--        <a-form-model-item label="发票抬头">-->
        <!--          <a-input readOnly v-model="invoiceForm.header" />-->
        <!--        </a-form-model-item>-->
        <!--        <a-form-model-item label="发票类型">-->
        <!--          <a-input readOnly v-model="typeOpts[invoiceForm.invoice_type]" />-->
        <!--        </a-form-model-item>-->
        <!--        <a-form-model-item label="统一社会信用代码">-->
        <!--          <a-input readOnly v-model="invoiceForm.social_code" placeholder="输入统一社会信用代码" />-->
        <!--        </a-form-model-item>-->
        <!--        <a-form-model-item label="开户银行名称">-->
        <!--          <a-input v-model="invoiceForm.bank_name" readOnly placeholder="输入开户银行名称" />-->
        <!--        </a-form-model-item>-->
        <!--        <a-form-model-item label="基本开户账号">-->
        <!--          <a-input v-model="invoiceForm.account_num" readOnly placeholder="输入基本开户账号" />-->
        <!--        </a-form-model-item>-->
        <!--        <a-form-model-item label="注册场所地址">-->
        <!--          <a-input v-model="invoiceForm.register_address" readOnly placeholder="输入注册场所地址" />-->
        <!--        </a-form-model-item>-->
        <!--        <a-form-model-item label="注册固定电话">-->
        <!--          <a-input v-model="invoiceForm.register_phone" readOnly placeholder="输入注册固定电话" />-->
        <!--        </a-form-model-item>-->
      </a-form-model>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
  import storage from 'store'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import { STable } from '@/components'
  import apis from '@/api'
  import invoiceColumns from '@/columns/invoice'
  import { getAddInfo, getCheck, getUnInvoice, postAddInfo } from '@/api/invoice'

  export default {
    components: {
      STable
    },
    name: 'InvoiceList',
    data () {
      return {
        tab: '1',
        invoiceColumns: invoiceColumns.invoiced,
        invoiceData: parameters => {
          return getUnInvoice(Object.assign(parameters, this.queryParam)).then(res => {
            this.adviserOpts = res.result.all_advisers
            return res.result
          })
        },
        searchText: '',
        searchInput: null,
        searchedColumn: '',
        visible: false,
        labelCol: { span: 8 },
        wrapperCol: { span: 12 },
        invoiceRules: {
          invoice_num: [{ required: true, pattern: /(?!^\d+$)(?!^[a-zA-Z]+$)[0-9a-zA-Z]{4,50}/, message: '必须填写正确的发票编号', trigger: 'blur' }],
          express_name: [{ required: true, pattern: /^[a-zA-Z\u4e00-\u9fa5]+$/, message: '必须填写正确的物流公司名称', trigger: 'blur' }],
          express_num: [{ required: true, pattern: /(?!^\d+$)(?!^[a-zA-Z]+$)[0-9a-zA-Z]{4,50}/, message: '必须填写正确的物流单号', trigger: 'blur' }]
        },
        invoiceForm: {},
        queryParam: {},
        advanced: true,
        header: {
          'Access-Token': storage.get(ACCESS_TOKEN)
        },
        uploadUrl: apis.Upload,
        exportUrl: apis.ExportInvoice,
        adviserOpts: {},
        accessToken: storage.get(ACCESS_TOKEN),
        company: storage.get('company'),
        typeOpts: {},
        visible2: false
      }
    },
    created () {
      this.queryParam['filter[status]'] = '40'
    },
    methods: {
      toDetail (id) {
        this.$router.push({ name: 'InvoiceDetail', params: { id } })
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      },
      resetSearch () {
        this.queryParam = {}
        this.queryParam['filter[created_at_start]'] = ''
        this.queryParam['filter[created_at_end]'] = ''
        this.queryParam['filter[check_time_start]'] = ''
        this.queryParam['filter[check_time_end]'] = ''
        this.$refs.table.refresh(true)
      },
      uploadModal (id) {
        const app = this
        app.invoiceForm = {}
        getAddInfo(id).then(res => {
          if (res.status === 0) {
            app.invoiceForm['invoice_id'] = id
            app.visible = true
          } else {
            app.$warning({
              title: res.msg
            })
          }
        })
      },
      submitUpload () {
        const app = this
        const data = {}
        app.$refs.invoiceForm.validate(valid => {
          if (valid) {
            for (const k in app.invoiceForm) {
              data['invoiceInfos[' + k + ']'] = app.invoiceForm[k]
            }
            postAddInfo(data, app.invoiceForm.invoice_id).then(res => {
              if (res.status === 0) {
                app.visible = false
                app.invoiceForm = {}
                app.$refs.table.refresh(true)
              } else {
                app.$warning({
                  title: res.msg
                })
              }
            })
          } else {
            return false
          }
        })
      },
      handleChange (info) {
        if (info.file.status === 'done') {
          this.invoiceForm['voice_electronic_file'] = info.file.response.result.url
        }
      },
      onCreateAt (date, dateString) {
        this.queryParam['filter[created_at_start]'] = dateString[0]
        this.queryParam['filter[created_at_end]'] = dateString[1]
      },
      onCheckAt (date, dateString) {
        this.queryParam['filter[check_time_start]'] = dateString[0]
        this.queryParam['filter[check_time_end]'] = dateString[1]
      },
      filterOption (input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        )
      },
      exportInvoice () {
        let params = this.exportUrl + '?access_token=' + this.accessToken + '&company=' + this.company
        for (const k in this.queryParam) {
          params = params + '&' + k + '=' + this.queryParam[k]
        }
        window.open(process.env.VUE_APP_API_BASE_URL + params)
      },
      getInvoice (id) {
        const app = this
        app.invoiceForm = {}
        getCheck(id).then(res => {
          const invoice = res.result.invoiceData
          app.typeOpts = res.result.invoice_type_opts
          for (const k in invoice) {
            app.invoiceForm[k] = invoice[k]
          }
        }).finally(() => {
          app.visible2 = true
        })
      }
    }
  }
</script>

<style scoped>

</style>
